package hlhj.fhp.supreme.activitys

import android.content.Context
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.WindowManager
import android.widget.ImageView
import android.widget.LinearLayout
import cn.jzvd.JZVideoPlayer
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import hlhj.fhp.supreme.BaseAty
import hlhj.fhp.supreme.R
import hlhj.fhp.supreme.javabean.BaseBean
import hlhj.fhp.supreme.javabean.ClassDetailBean
import hlhj.fhp.supreme.javabean.CommentBean
import hlhj.fhp.supreme.javabean.IsTeacherBean
import hlhj.fhp.supreme.network.Urls
import hlhj.fhp.supreme.utils.JsonCallBack
import hlhj.fhp.supreme.utils.MyUtils
import kotlinx.android.synthetic.main.activity_jie_pan_video_detal_aty.*
import android.content.Context.INPUT_METHOD_SERVICE
import android.view.View
import android.view.inputmethod.InputMethodManager
import cn.sharesdk.framework.Platform
import cn.sharesdk.framework.PlatformActionListener
import cn.sharesdk.onekeyshare.OnekeyShare
import fhp.hlhj.giantfold.utils.ToastUtils
import hlhj.fhp.supreme.adapters.ReplyAdp
import hlhj.fhp.supreme.customview.DashangDialog
import hlhj.fhp.supreme.customview.MyListView
import java.util.*
class ClassVedioAty : BaseAty() {
    var url = ""
    var pid=""
    var isTeacher=false;
    var tittle=""
    var imgUrl = "http://p.qpic.cn/videoyun/0/2449_43b6f696980311e59ed467f22794e792_1/640"
    private lateinit var commentAdp:BaseQuickAdapter<CommentBean.DataBean.NewBean,BaseViewHolder>
    private lateinit var moreAdp:BaseQuickAdapter<String,BaseViewHolder>
    private val commentDatas=ArrayList<CommentBean.DataBean.NewBean>()
    private val moreDatas=ArrayList<String>()
    override fun getContentId(): Int = R.layout.activity_jie_pan_video_detal_aty

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
    }
    override fun initView() {
        videoPlayer.setUp(url, JZVideoPlayer.SCREEN_WINDOW_NORMAL,"")
        moreAdp=object :BaseQuickAdapter<String,BaseViewHolder>(R.layout.jiepan_video_more_item,moreDatas){
            override fun convert(helper: BaseViewHolder?, item: String?) {
            }
        }

        moreRcy.adapter=moreAdp
        moreRcy.layoutManager=LinearLayoutManager(this@ClassVedioAty,LinearLayout.HORIZONTAL,false)
        /*评论*/
        commentAdp=object :BaseQuickAdapter<CommentBean.DataBean.NewBean,BaseViewHolder>(R.layout.option_comment_item,commentDatas){
            override fun convert(helper: BaseViewHolder?, item: CommentBean.DataBean.NewBean?) {
                Glide.with(mContext).load(item?.avatar).asBitmap().into(helper?.getView(R.id.itemIcon))
                helper?.setText(R.id.itemName,item?.full_name)
                helper?.setText(R.id.itemContent,item?.content)
                helper?.setText(R.id.itemTime,MyUtils.convertTimeToFormat(item?.create_time!!.toLong()))
                val btRep = helper?.getView<ImageView>(R.id.btRep)
                val listView = helper?.getView<MyListView>(R.id.listView)
                if (item?.son!=null){
                    listView?.visibility=View.VISIBLE
                    val adp = ReplyAdp(mContext,item?.son as ArrayList<CommentBean.DataBean.NewBean.SonBean>)
                    listView?.adapter=adp
                }else{
                    listView?.visibility=View.GONE
                }

                btRep?.setOnClickListener {
                    if (isTeacher){
                        etContent.setFocusable(true);
                        etContent.setFocusableInTouchMode(true);
                        etContent.requestFocus();
                        pid=item?.id.toString()
                        val inputManager = etContent.getContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                        inputManager.showSoftInput(etContent,0)
                    }else{
                        MyUtils.toast("只有老师能够回复别人")
                    }
                }
            }
        }

        recyclerview.adapter=commentAdp
        recyclerview.layoutManager=LinearLayoutManager(this,LinearLayout.VERTICAL,true)

        disPatchData()
    }
    //**获取数据
    private fun disPatchData() {
        OkGo.post<ClassDetailBean>(Urls.BaseUrl+Urls.CLASS_DETAIL)
                .params("id",intent.getStringExtra("id"))
                .execute(object :JsonCallBack<ClassDetailBean>(this){
                    override fun onSuccess(response: Response<ClassDetailBean>?) {
                        val bean = response?.body()
                        if (bean?.code==1){
                            tvClasses.text="已上传：${bean?.data.teacher_num}课"
                            tittle=bean?.data.title
                            videoPlayer.setUp(bean?.data.src, JZVideoPlayer.SCREEN_WINDOW_NORMAL,bean?.data.title)
                            JZVideoPlayer.FULLSCREEN_ORIENTATION = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
                            JZVideoPlayer.NORMAL_ORIENTATION = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
                            Glide.with(this@ClassVedioAty).load(bean?.data.teacher_img).into(writerIcon)
                            writerName.text=bean?.data.teacher_name
                            writerInfo.text="老师简介：${bean?.data.teacher_des}"
                        }
                    }
                })
        disPatchComment()
        OkGo.post<IsTeacherBean>(Urls.BaseUrl+Urls.ISTEACH)
                .execute(object :JsonCallBack<IsTeacherBean>(this){
                    override fun onSuccess(response: Response<IsTeacherBean>?) {
                        val bean = response?.body()
                        if (bean?.code==1){
                            if (bean?.data.status==2){
                                isTeacher=true
                            }else{
                            }
                        }
                    }
                })
    }

    /**
     * 获取评论
     */
    private fun disPatchComment() {
        OkGo.post<CommentBean>(Urls.BaseUrl + Urls.CommentList)
                .params("object_id", intent.getStringExtra("id"))
                .params("type", 3)
                .execute(object : JsonCallBack<CommentBean>(this) {
                    override fun onSuccess(response: Response<CommentBean>?) {
                        val bean = response?.body()
                        if (bean?.code == 1) {
                            if (bean?.data != null) {
                                if (bean?.data.newX != null) {
                                    if (bean?.data.hot != null) {
                                        for (i in 0..bean?.data.hot.size-1){
                                            val newBean = CommentBean.DataBean.NewBean()
                                            val hotBean = bean?.data.hot[i]
                                            val son = ArrayList<CommentBean.DataBean.NewBean.SonBean>()
                                            for (j in 0..hotBean.son.size-1){
                                                val sonBean = CommentBean.DataBean.NewBean.SonBean()
                                                val hson = hotBean.son[j]
                                                sonBean.content=hson.content
                                                sonBean.create_time=hson.create_time
                                                sonBean.full_name=hson.full_name
                                                sonBean.id=hson.id
                                                son.add(sonBean)
                                            }
                                            newBean.content= hotBean.content
                                            newBean.full_name=hotBean.full_name
                                            newBean.avatar=hotBean.avatar
                                            newBean.create_time=hotBean.create_time
                                            newBean.id=hotBean.id
                                            newBean.son=son
                                            bean?.data.newX.add(newBean)
//                                            bean?.data.newX.addAll(bean?.data.hot as ArrayList<CommentBean.DataBean.NewBean>)
                                        }

                                    }
                                    commentDatas.addAll(bean?.data.newX)
                                    commentAdp.notifyDataSetChanged()
                                }
                            }

                        }
                    }
                })
    }

/*    private fun initHeadVideo() {
        videoPlayer.setUp(url, JZVideoPlayer.SCREEN_WINDOW_NORMAL,"嫂子闭眼睛")
        JZVideoPlayer.FULLSCREEN_ORIENTATION = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
        JZVideoPlayer.NORMAL_ORIENTATION = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
    }*/

    override fun onPause() {
        super.onPause()
        JZVideoPlayer.releaseAllVideos()
    }

    override fun onBackPressed() {
        if (JZVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed()
    }

    override fun initListener() {
        btShare.setOnClickListener {
            val listener=object : PlatformActionListener {
                override fun onComplete(p0: Platform?, p1: Int, p2: HashMap<String, Any>?) {
                    OkGo.post<BaseBean>(Urls.BaseUrl+Urls.SHARE)
                            .execute(object :JsonCallBack<BaseBean>(this@ClassVedioAty){
                                override fun onSuccess(response: Response<BaseBean>?) {
                                    val bean = response?.body()
                                    if (bean?.code==1){
                                        ToastUtils.toast(this@ClassVedioAty,"分享成功")
                                    }else{
                                        ToastUtils.toast(this@ClassVedioAty,bean?.msg!!)
                                    }
                                }
                            })
                }
                override fun onCancel(p0: Platform?, p1: Int) {
                    ToastUtils.toast(this@ClassVedioAty,"分享已取消")
                }
                override fun onError(p0: Platform?, p1: Int, p2: Throwable?) {
                    ToastUtils.toast(this@ClassVedioAty,"分享失败")
                }
            }
            val oks = OnekeyShare()
            oks.callback=listener
            oks.setTitle(tittle)
            // titleUrl是标题的网络链接，仅在Linked-in,QQ和QQ空间使用
            oks.setTitleUrl("https://www.baidu.com/")
            // text是分享文本，所有平台都需要这个字段
            oks.text = "志尚课堂，学会怎么赚钱"
            //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
            oks.setImageUrl("http://zhishang.hlhjapp.com/static/images/logo.png")
            // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
            //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
            // url仅在微信（包括好友和朋友圈）中使用
            oks.setUrl("https://www.baidu.com/")
            // comment是我对这条分享的评论，仅在人人网和QQ空间使用
            oks.show(this)
        }
        showEt.setOnClickListener {
            pid=""
            val inputManager = etContent.getContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            inputManager.showSoftInput(etContent,0)
        }
        btExit.setOnClickListener {
            finish()
        }
        btComment.setOnClickListener {
            if (etContent.text.isEmpty()){
            }else{
                OkGo.post<BaseBean>(Urls.BaseUrl+Urls.HUIFU)
                        .params("object_id",intent.getStringExtra("id"))
                        .params("type",3)
                        .params("content",etContent.text.toString())
                        .params("parent_id",pid)
                        .execute(object :JsonCallBack<BaseBean>(this@ClassVedioAty){
                            override fun onSuccess(response: Response<BaseBean>?) {
                                val bean = response?.body()
                                if (bean?.code==1){
                                    etContent.setText("")
                                    MyUtils.toast("评论成功")
                                    commentDatas.clear()
                                    disPatchComment()
                                }
                            }
                        })
            }
        }
        btGive.setOnClickListener {
            val dashangDialog = DashangDialog(this,2,intent.getStringExtra("id").toInt())
            dashangDialog.show()

        }
    }
}
